package beans;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;

import com.sun.org.apache.xerces.internal.impl.dtd.models.CMAny;

import beans.Query1;

import web.Populate;

public class Parallel {
	private DefaultHttpClient client;
	private HttpGet get;
	private static Connection con=null;
	private Statement st= null;
//	private static Parallel instance=null;
	private ExecutorService threadpool;
	private SchemeRegistry schemeRegistry;
	private ClientConnectionManager cm;
	private Timer timer;
	
	public Parallel(){
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
		cm = new ThreadSafeClientConnManager(schemeRegistry);
		client = new DefaultHttpClient(cm);
		get = new HttpGet();
		threadpool = Executors.newSingleThreadExecutor();
		timer = new Timer();
        timer.schedule(new ShutdownThreadPool(), 60*1000);
		try {
			con=DBConnection.getDataSource().getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	class ShutdownThreadPool extends TimerTask {
        public void run() {
        	cm.closeIdleConnections(60, TimeUnit.SECONDS);
            threadpool.shutdown();
            timer.cancel();
        }
    }
	
	
	//Richiesta da inviare ad opodo parallelamente alla query sul db 
	public void parallelRequest(String iataDep, String iataArriv, String mese, String giorno, String anno){
//		System.out.println("parReq: "+iataDep+" "+iataArriv+" "+giorno+" "+mese+" "+anno);
		try {
			threadpool.execute(new Thread(new Populate(iataDep,iataArriv,anno,mese,giorno,st,con,0,get,client)));
		} catch (Exception e) {
			threadpool.shutdownNow();
		}
	}
}
